#!/usr/bin/env python

"""
#ID Format: (Second generation)

 110102  YYYYMMDD    888        X
|-Addr-|--birth--|--order--|-checksum-|
  6bit    8bit      3bit       1bit

#Details:
*Address code refers to the resident's location,
where administrative divisions (including cities, banners,
and districts) have their own specific codes.
(For example, the code for Xicheng District in Beijing is 110102.)
*Date of Birth in the form YYYY-MM-DD.
*Order code is the code used to disambiguate people
with the same date of birth and address code.
Men are assigned to odd numbers, women assigned to even numbers.

#Alogrithm of the checksum:
The Checksum is the final digit, which confirms the validity
of the ID number from the first 17 digits,
utilizing ISO 7064:1983, MOD 11-2.

The checksum is obtained by:
*Marking the Identity card number right-to-left:

    a1, a2, ... , a18.

a1 for the parity-check codes;
*Weight coefficient calculation Wi = pow(2, i-1) mod 11;

i  18 17 16 15 14 13 12 11 10 09 08 07 06 05 04 03 02 01
Wi  7  9 10  5  8  4  2  1  6  3  7  9 10  5  8  4  2  1

*Calculation of S = sum(i=2, 18)(ai*Wi)
*Finally, a1 = (12 - (S mod 11)) mod 11

@version: $Id$
@author: U{vie<mailto:viechang@gmail.com>}
@see: http://en.wikipedia.org/wiki/Resident_Identity_Card#Identity_card_number
"""

import math
import sys

"""
@param: rid: str of a valid ID.
@return: checksum.
"""
def calcChecksum(rid):
    len_rid = len(rid)
    workArr = list(rid)
    workArr.reverse()
    def W(i):
        return int(math.pow(2, i-1) % 11)
    def S():
        sum = 0
        for j in range(0, len_rid):
            sum += int(workArr[j]) * W(j+2)
        return sum
    return (12 - (S() % 11)) % 11

if __name__ == "__main__":
    #test data.
    _TEST_DEF = '12010619861118001'
    _LEN_ID = len(_TEST_DEF)
    
    #debug flag.
    _DEBUG = 0

    #invalid input limit.
    _MAX_INVALID = 4
    count_invalid = 0

    #input an valid ID from terminal.
    while(True):
        try:
            id = raw_input('\n' + 'Please input an ID with 17 bit: ')
        except ValueError:
            print('Value-error.')

        if _DEBUG:
            print len(id)
        if (len(id) != _LEN_ID):
            if (count_invalid >= _MAX_INVALID):
                if _DEBUG:
                    id = _TEST_DEF
                    print(id)
                    break
                else:
                    print('\n'
                          + 'The number of attempts exceeds the maximum limit.')
                    sys.exit(1)
            count_invalid += 1
            print('Invalid input({0}times). Please retry.'.format(count_invalid))
            continue
        else:
            print('\n' + 'Valid input: {0}'.format(id))
            break

    #process and echo the result.
    ret_val = calcChecksum(id)
    print('Checksum: {0}'.format(ret_val))
